package cn.gjxblog.scheduling.jdk.executor;

import cn.gjxblog.base.LogUtils;
import cn.gjxblog.base.ThreadUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@RunWith(JUnit4.class)
public class TestScheduledThreadPoolExecutor {

    ScheduledThreadPoolExecutor executor =new ScheduledThreadPoolExecutor(1);
    /**
     * 自定义创建线程工厂
     */
    ScheduledThreadPoolExecutor executor2 =new ScheduledThreadPoolExecutor(2, new ThreadFactory() {
        AtomicInteger atomicInteger =   new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("myTask-" + atomicInteger.getAndIncrement());
            return thread;
        }
    });

    @Test
    public void test1(){
        LogUtils.printThreadInfo();
        executor.schedule(new MyRunableTask(1+""),1, TimeUnit.SECONDS);
        executor.schedule(new MyRunableTask(2+""),1, TimeUnit.SECONDS);
        ThreadUtils.sleep(30);
    }

    @Test
    public void test2(){
        LogUtils.printThreadInfo();
        executor2.schedule(new MyRunableTask(1+""),1, TimeUnit.SECONDS);
        executor2.schedule(new MyRunableTask(2+""),1, TimeUnit.SECONDS);
        ThreadUtils.sleep(30);
    }

    /**
     * 调度 Callable 类型的作业
     */
    @Test
    public void test3() throws ExecutionException, InterruptedException {
        LogUtils.printThreadInfo();
        ScheduledFuture schedule = executor2.schedule(new MyCallableTask( "1"), 1, TimeUnit.SECONDS);
        System.out.println(schedule.get());
        ThreadUtils.sleep(30);
    }

    /**
     * scheduleAtFixedRate
     *
     * 执行周期固定为
     * initialDelay,initialDelay + period,initialDelay + 2 * period  ... initialDelay + N * period
     * 如果执行任务时间在对应的执行周期时间之后，任务需要立即执行。在周期时间之前等待执行。
     */
    @Test
    public void test4()  {
        LogUtils.printThreadInfo();
        executor2.scheduleAtFixedRate(new MyRunableTask("1"),1,1,TimeUnit.SECONDS);
//        executor2.scheduleAtFixedRate(new MyRunableTask("2"),1,1,TimeUnit.SECONDS);
        ThreadUtils.sleep(30);
    }

    /**
     * scheduleWithFixedDelay
     *
     * 执行周期
     * 第一次任务时间为   当前时间 + initialDelay
     * 第二次之后执行任务时间为   上次任务结束时间 + delay
     */
    @Test
    public void test5()  {
        LogUtils.printThreadInfo();
        executor2.scheduleWithFixedDelay(new MyRunableTask("1"),2,1, TimeUnit.SECONDS);
        ThreadUtils.sleep(30);
    }
}
